package com.example.gate.controller;

import com.example.gate.listener.ServiceChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务监控控制器
 * 提供手动检查服务状态的功能
 */
@Slf4j
@RestController
@RequestMapping("/api/monitor")
public class ServiceMonitorController {

    private final DiscoveryClient discoveryClient;
    private final ServiceChangeListener serviceChangeListener;

    public ServiceMonitorController(DiscoveryClient discoveryClient, ServiceChangeListener serviceChangeListener) {
        this.discoveryClient = discoveryClient;
        this.serviceChangeListener = serviceChangeListener;
    }

    /**
     * 手动触发服务状态检查
     */
    @PostMapping("/check")
    public Map<String, Object> manualCheck() {
        log.info("收到手动服务状态检查请求");
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "手动检查已触发");
        result.put("timestamp", System.currentTimeMillis());
        
        // 触发手动检查
        serviceChangeListener.manualCheck();
        
        return result;
    }

    /**
     * 获取所有服务状态
     */
    @GetMapping("/services")
    public Map<String, Object> getAllServices() {
        Map<String, Object> result = new HashMap<>();
        
        List<String> services = discoveryClient.getServices();
        Map<String, Object> serviceStatus = new HashMap<>();
        
        for (String serviceName : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
            Map<String, Object> serviceInfo = new HashMap<>();
            serviceInfo.put("instanceCount", instances.size());
            serviceInfo.put("available", !instances.isEmpty());
            serviceInfo.put("instances", instances.stream()
                    .map(instance -> {
                        Map<String, Object> instanceInfo = new HashMap<>();
                        instanceInfo.put("host", instance.getHost());
                        instanceInfo.put("port", instance.getPort());
                        instanceInfo.put("uri", instance.getUri().toString());
                        instanceInfo.put("metadata", instance.getMetadata());
                        return instanceInfo;
                    })
                    .collect(Collectors.toList()));
            
            serviceStatus.put(serviceName, serviceInfo);
        }
        
        result.put("services", serviceStatus);
        result.put("totalServices", services.size());
        result.put("timestamp", System.currentTimeMillis());
        
        return result;
    }

    /**
     * 获取指定服务状态
     */
    @GetMapping("/services/{serviceName}")
    public Map<String, Object> getServiceStatus(@PathVariable String serviceName) {
        Map<String, Object> result = new HashMap<>();
        
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        
        result.put("serviceName", serviceName);
        result.put("instanceCount", instances.size());
        result.put("available", !instances.isEmpty());
        result.put("instances", instances.stream()
                .map(instance -> {
                    Map<String, Object> instanceInfo = new HashMap<>();
                    instanceInfo.put("host", instance.getHost());
                    instanceInfo.put("port", instance.getPort());
                    instanceInfo.put("uri", instance.getUri().toString());
                    instanceInfo.put("metadata", instance.getMetadata());
                    return instanceInfo;
                })
                .collect(Collectors.toList()));
        result.put("timestamp", System.currentTimeMillis());
        
        return result;
    }

    /**
     * 获取lobby服务状态
     */
    @GetMapping("/lobby-status")
    public Map<String, Object> getLobbyStatus() {
        Map<String, Object> result = new HashMap<>();
        
        int instanceCount = serviceChangeListener.getCurrentLobbyInstanceCount();
        boolean available = serviceChangeListener.isLobbyServiceAvailable();
        
        result.put("serviceName", "lobby-service");
        result.put("instanceCount", instanceCount);
        result.put("available", available);
        result.put("lastChangeTime", serviceChangeListener.getLastChangeTime("lobby-service"));
        result.put("timestamp", System.currentTimeMillis());
        
        return result;
    }
} 